<?php

namespace App\Jobs;

use App\Helpers\Api\MiniProgramTrait;
use App\Models\Cookbook;
use App\Models\NewUrl;
use App\Models\Product;
use App\Models\User;
use EasyWeChat\Kernel\Messages\Article;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Intervention\Image\Facades\Image;

//
class NewsUrl implements ShouldQueue
{
    use MiniProgramTrait;

    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 60;

    public $tries = 1;


    private $type;
    private $id;
    private $user_id;
    private $insert_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($type, $id, $user_id, $insert_id)
    {
        $this->type = $type;
        $this->id = $id;
        $this->user_id = $user_id;
        $this->insert_id = $insert_id;
    }


    public function handle()
    {
        \Log::info("==============start news url job =========================");
        $app = $this->official();
        $appid = env('WECHAT_MINI_PROGRAM_APPID', 'wx9f04b86057e5aff7');
        $mini_daren_path = '/pages/transfer/index?merchant_id=' . $this->user_id;

        if ($this->type == 'cookbook') {
            $title = '更多做饭小技巧>>>【厨友会食谱】';
            $digest = '点击下方视频，解锁更多做饭小技巧';
            $model = Cookbook::find($this->id);
            $file = $model->video_url . "?vframe/jpg/offset/0/width/50";
            $price = 0;
            $product_tile = $model->title;
            $mini_path = 'package-recipe/pages/detail/index?id='.$this->id.'&merchant_id=' . $this->user_id;
        } else if($this->type == 'product') {
            $title = '购买视频中同款商品>>>【厨友会严选好物】';
            $digest = '点击下方图片，购买同款厨友会严选好物';
            $model = Product::find($this->id);
            $file = $model->image_url[0]['cover'];
            $product_tile = $model->title;
            $price = $model->vip_amount_yuan;
            $mini_path = 'package-shop/pages/shop-detail/index?id=' . $this->id.'&merchant_id=' . $this->user_id;
        } else {
            $title = '视频号专属福利>>>【厨友会新人专享】';
            $digest = '点击下方图片，0元领取视频号专享福利';
            $file = '0元活动新人专享';
            $product_tile = '0元领取视频号专享福利';
            $model = null;
            $price = 0;
            $mini_path = 'pages/zero/index?merchant_id=' . $this->user_id;
        }

        if (in_array($this->type, ['product', 'cookbook'])) {
            if (! ($thumb_media_id = $model->thumb_media_id) ||  !($wx_media_url = $model->wx_media_url)) {
                $url = $this->downloadImage($file);
                Image::make($url)->resize(1080, 864)->save($url);
                $result = $app->material->uploadImage($url);
                $thumb_media_id = $result['media_id'];
                $wx_media_url = $result['url'];
                $model->thumb_media_id = $thumb_media_id;
                $model->wx_media_url =  $wx_media_url;
                $model->save();
                unlink($url);
            }
        } else {
            $thumb_media_id = 'VyB2qNuTjcu9OWLUdip7SpQLVKDv9e235pcREC3OI0E';
            $wx_media_url = 'https://mmbiz.qpic.cn/mmbiz_jpg/VzZeDLc6IXyp4oeEb71D1MDL07lbSFSI2KOJ7Z5YBuKn0gicbIoIqh1wDllicdDc6s0ac6QQsDI9uIp2PFRNhMSA/640?wx_fmt=jpeg';
        }

        $user = User::find($this->user_id);
        $content = '<p><span data-shimo-docs="[['.$digest.']]"></span></p><p line="Wy7I" style="line-height: 1.7;margin-bottom: 0pt;margin-top: 0pt;font-size: 11pt;color: #494949;"><span line-inline="0YT0">'.$digest.'</span></p><p><mp-miniprogram data-miniprogram-appid="'.$appid.'" data-miniprogram-path="'.$mini_path.'" '
    .'data-miniprogram-nickname="厨友会" '
    .'data-miniprogram-avatar="http://mmbiz.qpic.cn/mmbiz_png/BWEfWaRdUClqbfUagiaHAefYEEAG1YDswc0M1rJrh1LEfg2YJWGQuaUPOUYjAueGCNHOxTrfAa24IWKoS3cgdhw/640?wx_fmt=png&wxfrom=200"'
    .' data-miniprogram-title="严选好物" data-miniprogram-imageurl="'.$wx_media_url.'" '
    .'data-miniprogram-type="card" data-miniprogram-servicetype="0"></mp-miniprogram></p>';

        if ($this->type != 'cookbook') {
            $content .= '<p>￥'.$price.'</p>';
        }
        $content .= '<p><br  /></p><p>'.$product_tile.'<br  /></p><p><a class="weapp_text_link js_weapp_entry" style="font-size:17px;" '
        .'data-miniprogram-appid="'.$appid.'" data-miniprogram-path="'.$mini_daren_path.'" data-miniprogram-nickname="厨友会" href="" data-miniprogram-type="text" data-miniprogram-servicetype="" href="">点击开启您的视频号变现</a></p> ';

        $article = new Article([
            'thumb_media_id' => $thumb_media_id,
            'author' => $user->nickname,
            'title' => $title,
            'digest' => $digest,
            'content' => $content,
            'show_cover' => 0,
        ]);
        $article_material = $app->material->uploadArticle($article);
        if (!isset($article_material['media_id'])) {
            $data['status'] = 2;
            \Log::info(var_export($article_material, true));
            $msg_id = 0;
        } else {
            $media_id = $article_material['media_id'];
            $result = $app->broadcasting->sendNews($media_id, ['oqvqnwsAPVPcLO2ISX-tdjsZI9Sc', 'oqvqnwsAPVPcLO2ISX-tdjsZI9Sc']);
            if ($result['errcode'] != 0) {
                $data['status'] = 2;
                \Log::error('news_url_error' . var_export($result, true));
            }
            $msg_id = $result['msg_id'];
        }
        $data['msg_id'] = $msg_id;
        NewUrl::where('id', $this->insert_id)->update($data);
        \Log::info("==============end news url job ============================");
    }

    private function downloadImage($url)
    {
        $path = public_path('./images/');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = time() . rand(0, 10000);
        $extendsion = pathinfo($url, PATHINFO_EXTENSION) ?: 'jpg';
        $filename .= "." . $extendsion;
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        return $path . $filename;
    }
}
